package drds.configuration.web.tools;

import drds.configuration.web.build_model.ColumnToPropertyUtil;
import drds.configuration.web.task.JdbcUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class BuildTableModel {

    private static String newLine = "\n";

    /**
     * 一个表一个类
     */
    public static void main(String[] args) throws Exception {
        String path = "E:/czh/p/model_file";
        String ymdhms = "yyyy-MM-dd";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ymdhms);
        String filePath = path + File.separator + simpleDateFormat.format(new Date()) + File.separator + System.currentTimeMillis() + File.separator;
        File file = new File(filePath);
        file.getParentFile().mkdirs();
        file.mkdirs();
        List<String> objectList = new ArrayList<String>();
        objectList.add("quartzjob_job");
        objectList.add("quartzjob_job_class");
        objectList.add("quartzjob_job_class_parameter");
        objectList.add("quartzjob_job_log");
        objectList.add("quartzjob_job_parameter_value");

        String packageName = "quartzjob";
        for (String object :
                objectList) {
            table(object, filePath, packageName);
            System.out.println("#######################################");
        }
    }

    private static void table(String tableName, String filePath, String packageName) throws Exception {
        //    url=jdbc:mysql://127.0.0.1/drds_home?characterEncoding=utf8&useSSL=false
        //    username=root
        //    password=root

        String className = ColumnToPropertyUtil.columnToProperty(tableName.replaceFirst(packageName.toLowerCase(), ""));
        className.substring(0, 1).toUpperCase();
        className = className.substring(0, 1).toUpperCase() + className.substring(1);
        try {
            Class.forName("org.mariadb.jdbc.Driver");
        } catch (Exception e) {

        }

        String databaseName = "drds_home_201804180923";
        String url = "jdbc:mysql://127.0.0.1/" + databaseName + "?characterEncoding=utf8&useSSL=false";
        String username = "root";
        String password = "root";

        List<Object> objectList = new ArrayList<Object>();
        objectList.add(tableName);

        Connection connection = DriverManager.getConnection(url, username, password);
        List<Map<String, Object>> mapList = JdbcUtil.get(connection, "select t.* from INFORMATION_SCHEMA.Columns  t where t.TABLE_SCHEMA='drds_home_201804180923' and t.table_name=?", objectList);
        connection.close();
        System.out.println(mapList.size());
        File file = new File(filePath, className + ".java");
        FileWriter fileWriter = new FileWriter(file, true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);


        String firstColumnName = ((String) mapList.get(0).get("column_name"));
        for (Map<String, Object> map :
                mapList) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            }
            System.out.println(map.get("column_name") + "," + map.get("data_type"));
        }


        //        CREATE TABLE `model_table` (
        //  `id` bigint(20) NOT NULL AUTO_INCREMENT,
        //  `add_date_time` varchar(20) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
        //  `add_date_time_long` bigint(20) NOT NULL DEFAULT 0,
        //  `add_date_time_timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
        //  `update_date_time` varchar(20) COLLATE utf8mb4_bin NOT NULL DEFAULT '',
        //  `update_date_time_long` bigint(20) NOT NULL DEFAULT 0,
        //  `update_date_time_timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE current_timestamp(),
        //  `version` bigint(20) NOT NULL DEFAULT 0,
        //            PRIMARY KEY (`id`)
        //) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
        //判断是否存在上面的字段如果存在上面的8个自动则进行基础信息校验
        List<String> baseColumnNameList = new ArrayList<String>();
        baseColumnNameList.add("id");
        //
        baseColumnNameList.add("add_date_time");
        baseColumnNameList.add("add_date_time_long");
        baseColumnNameList.add("add_date_time_timestamp");
        //
        baseColumnNameList.add("update_date_time");
        baseColumnNameList.add("update_date_time_long");
        baseColumnNameList.add("update_date_time_timestamp");
        //
        baseColumnNameList.add("version");//如果未来需要增加则直接修改代码

        boolean isNotMatchAllColumnName = false;
        for (String columnName : baseColumnNameList) {

            boolean notFind = true;//只要一个不存在则不需要
            for (Map<String, Object> map :
                    mapList) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                    //System.out.println(map.get("column_name") + "," + map.get("data_type"));


                    String column_name = (String) map.get("column_name");
                    if (columnName.equals(column_name)) {
                        notFind = false;
                        break;
                    }

                }


            }
            if (notFind) {
                isNotMatchAllColumnName = true;
                break;
            }
        }


        System.out.println("写入model");

//        package beautiful.butterfly.tool.plus.web.table_model.drds_home.datanode;
//
//        import beautiful.butterfly.tool.plus.db.table_model.*;
//        import GroupDataSourceId;
//        import lombok.Getter;
//        import lombok.Setter;
//
//        import java.sql.Timestamp;
//
//        @Table(groupDataSourceId = GroupDataSourceId.DRDS_HOME,//
//                tableName = Datanode.__TABLE_NAME__,//
//                primaryKey = Datanode.ID,//
//                checkBaseColumn = TableInfo.TRUE)//
//        public class Datanode extends Model
//        {
//            public static final String __TABLE_NAME__ = "datanode_datanode";
//            //公共字段start
//            @ColumnName
//            public static final String ID = "id";
//            @ColumnName
//            public static final String ADD_DATE_TIME = "add_date_time";
//            @ColumnName
//            public static final String ADD_DATE_TIME_LONG = "add_date_time_long";
//            @ColumnName
//            public static final String ADD_DATE_TIME_TIMESTAMP = "add_date_time_timestamp";
//            //*
//            @ColumnName
//            public static final String UPDATE_DATE_TIME = "update_date_time";
//            @ColumnName
//            public static final String UPDATE_DATE_TIME_LONG = "update_date_time_long";
//            @ColumnName
//            public static final String UPDATE_DATE_TIME_TIMESTAMP = "update_date_time_timestamp";
//            @ColumnName
//            public static final String VERSION = "version";
//            public static Datanode dao = new Datanode();
//            @Setter
//            @Getter
//            @Field(withColumnName = ID)
//            private Long id;
//            @Setter
//            @Getter
//            @Field(withColumnName = ADD_DATE_TIME)
//            private String addDateTime;
//            @Setter
//            @Getter
//            @Field(withColumnName = ADD_DATE_TIME_LONG)
//            private Long addDateTimeLong;
//            @Setter
//            @Getter
//            @Field(withColumnName = ADD_DATE_TIME_TIMESTAMP)
//            private Timestamp addDateTimeTimestamp;
//            @Setter
//            @Getter
//            @Field(withColumnName = UPDATE_DATE_TIME)
//            private String updateDateTime;
//            @Setter
//            @Getter
//            @Field(withColumnName = UPDATE_DATE_TIME_LONG)
//            private Long updateDateTimeLong;
//            @Setter
//            @Getter
//            @Field(withColumnName = UPDATE_DATE_TIME_TIMESTAMP)
//            private Timestamp updateDateTimeTimestamp;
//            @Setter
//            @Getter
//            @Field(withColumnName = VERSION)
//            private Long version;
//            //公共字段end
//        }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


        bufferedWriter.write("package beautiful.butterfly.tool.plus.web.table_model.drds_home." + packageName + ";" + newLine);
//
        bufferedWriter.write(newLine);
        bufferedWriter.write("import beautiful.butterfly.tool.plus.db.table_model.*;" + newLine);
        bufferedWriter.write("import GroupDataSourceId;" + newLine);
        bufferedWriter.write("import lombok.Getter;" + newLine);
        bufferedWriter.write("import lombok.Setter;" + newLine);
        bufferedWriter.write("import java.sql.Timestamp;" + newLine);
        bufferedWriter.write("import java.sql.Date;" + newLine);

        bufferedWriter.write(newLine);
//
        bufferedWriter.write("@Table(groupDataSourceId = GroupDataSourceId.DRDS_HOME,//" + newLine);
        bufferedWriter.write("tableName = beautiful.butterfly.tool.plus.web.table_model.drds_home." + packageName + "." + className + ".__TABLE_NAME__,//" + newLine);
        bufferedWriter.write("primaryKey = beautiful.butterfly.tool.plus.web.table_model.drds_home." + packageName + "." + className + "." + firstColumnName.toUpperCase() + ",//" + newLine);//一般是第一个列

        String checkBaseColumn = isNotMatchAllColumnName ? "TableInfo.FALSE" : "TableInfo.TRUE";
        bufferedWriter.write("checkBaseColumn = " + checkBaseColumn + ")//" + newLine);//一般为TRUE
        bufferedWriter.write("public class " + className + " extends Model" + newLine);
        bufferedWriter.write("{" + newLine);
        bufferedWriter.write("public static final String __TABLE_NAME__ = \"" + tableName.toLowerCase() + "\";" + newLine);
        bufferedWriter.write("//公共字段start" + newLine);


        bufferedWriter.write("public static " + className + " dao = new " + className + "();" + newLine);
        bufferedWriter.write(newLine);

        for (Map<String, Object> map :
                mapList) {

            String column_name = (String) map.get("column_name");
            bufferedWriter.write("@ColumnName" + newLine);
            bufferedWriter.write("public static final String " + column_name.toUpperCase() + " = \"" + column_name.toLowerCase() + "\";" + newLine);
        }

        //
        for (Map<String, Object> map :
                mapList) {
//            for (Map.Entry<String, Object> entry : map.entrySet())
//            {
//                //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//            }
            System.out.println(map.get("column_name") + "," + map.get("data_type"));

            String column_name = (String) map.get("column_name");

            String data_type = (String) map.get("data_type");
            // Integer Long String  BigDecimal Date
            String columntype = "";
            if (data_type.contains("int") && !data_type.contains("bigint")) {
                columntype = "Integer";
            } else if (data_type.contains("bigint")) {
                columntype = "Long";
            } else if (data_type.contains("varchar") || data_type.contains("char")) {
                columntype = "String";
            } else if (data_type.contains("decimal")) {
                columntype = "BigDecimal";
            } else if (data_type.contains("timestamp")) {
                columntype = "Timestamp";
            } else if (data_type.contains("date")) {
                columntype = "Date";
            } else if (data_type.contains("datetime")) {
                columntype = "Date";
            } else {
                System.out.println(data_type);
                throw new RuntimeException("else");
            }
            bufferedWriter.write(newLine);
            bufferedWriter.write("@Setter" + newLine);
            bufferedWriter.write("@Getter" + newLine);
            bufferedWriter.write("@Field(withColumnName = " + column_name.toUpperCase() + ")" + newLine);
            bufferedWriter.write("private " + columntype + " " + ColumnToPropertyUtil.columnToProperty(column_name) + ";");

        }


        bufferedWriter.write("            //公共字段end" + newLine);
        bufferedWriter.write("}" + newLine);


        bufferedWriter.flush();

        fileWriter.flush();


        fileWriter.close();
    }
}
